
"use client";
import { CourseFormType } from "@/configs/types";
import {
  Button,
  Form,
  FormInstance,
  Input,
  Radio,
  Select,
  message,
} from "antd";
import React, {  useEffect, useState } from "react";
import { getType, upload } from "@/api";
import UploadImg from "../UploadImg";
interface CourseFormProps {
  onFinish: (value: CourseFormType) => void;
  onFinishFailed: (value: any) => void;
  id?: number;
  imgUrl?: string;
  setImgUrl: Function;
  form?: FormInstance<any>;
}

const CourseForm = (props: CourseFormProps) => {
  const { onFinish, onFinishFailed, imgUrl, setImgUrl, id, form } = props;
  const [types, setTypes] = useState<any[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const getPostType = async () => {
    const res = await getType({ differ: "video" });
    res.data.code === 200 && setTypes(res.data.data.records);
  };

  useEffect(() => {
    getPostType();
  }, []);

  async function uploadImg(e: React.ChangeEvent<HTMLInputElement>) {
    setLoading(true);
    if (e.target.files) {
      const files = e.target.files[0];
      var formData = new FormData();
      formData.append("files", files);
      const response = await upload(formData);
      if (response.data.code === 200) {
        setImgUrl(response.data.data);
        setLoading(false);
        message.success(response.data.msg);
      } else {
        message.error(response.data.msg);
      }
    }
  }

  return (
    <Form
      form={form}
      layout="horizontal"
      onFinish={onFinish}
      onFinishFailed={onFinishFailed}
    >
      <Form.Item label="封面" name={"subjectHead"}>
        <UploadImg
          onChange={uploadImg}
          isLoading={loading}
          imgUrl={imgUrl}
        ></UploadImg>
      </Form.Item>

      <Form.Item label="课程名" name={"subjectName"}>
        <Input />
      </Form.Item>
      <Form.Item label="状态" name={"subjectStatus"}>
        <Radio.Group>
          <Radio value={0}> 待审核 </Radio>
          <Radio value={1}> 通过 </Radio>
          <Radio value={2}> 未通过 </Radio>
        </Radio.Group>
      </Form.Item>
      <Form.Item label="是否需要申请观看" name={"subjectIsApply"}>
        <Radio.Group>
          <Radio value={0}> 是 </Radio>
          <Radio value={1}> 否 </Radio>
        </Radio.Group>
      </Form.Item>
      <Form.Item label="课程类型" name={"subjectType"}>
        <Select placeholder={ '请选择课程类型'}>
          {types.map((item: any) => (
            <Select.Option value={item.typeName} key={item.id}>
              {item.typeName}
            </Select.Option>
          ))}
        </Select>
      </Form.Item>
      <Form.Item wrapperCol={{ offset: 5 }}>
        {id ? (
          <Button htmlType="submit" style={{ width: 200 }}>
            编辑
          </Button>
        ) : (
          <Button htmlType="submit" style={{ width: 200 }}>
            添加
          </Button>
        )}
      </Form.Item>
    </Form>
  );
};

export default CourseForm;
